package org.micode.common.base;

import org.micode.common.enums.ResultEnum;
import org.micode.common.config.ApplicationConfig;
import org.micode.common.domain.ApiResult;

public abstract class AbstractController {

    /**
     * 返回成功结果
     *
     * @return
     */
    protected <T> ApiResult<T> successResult() {
        return result(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getName());
    }

    /**
     * 返回成功结果带数据
     *
     * @param data
     * @return
     */
    protected <T> ApiResult<T> successResultWithData(T data) {
        ApiResult<T> result = successResult();
        result.setData(data);
        return result;
    }

    /**
     * 返回成功结果带数据
     *
     * @param data
     * @return
     */
    protected <T> ApiResult<T> successResultWithData(T data, String message) {
        ApiResult<T> result = successResult();
        result.setData(data);
        result.setMsg(message);
        return result;
    }

    /**
     * 返回成功结果
     *
     * @param message
     * @return
     */
    protected ApiResult successResult(String message) {
        return result(ResultEnum.SUCCESS.getCode(), message);
    }

    /**
     * 返回失败结果
     *
     * @param resultEnum
     * @return
     */
    protected <T> ApiResult<T> failResult(ResultEnum resultEnum) {
        return result(resultEnum.getCode(), resultEnum.getName());
    }

    /**
     * 返回失败结果(非法参数)
     */
    protected <T> ApiResult<T> failResultForInvalidParam(String errorMsg) {
        return result(ResultEnum.PARAM_INVALID.getCode(), errorMsg);
    }

    /**
     * 返回失败结果
     *
     * @param code
     * @param message
     * @return
     */
    protected <T> ApiResult<T> failResult(Integer code, String message) {
        return result(code, message);
    }

    /**
     * 结果
     *
     * @param code
     * @param msg
     * @return
     */
    private <T> ApiResult<T> result(Integer code, String msg) {
        ApiResult apiResult = new ApiResult();
        apiResult.setCode(code);
        apiResult.setMsg(msg);
        apiResult.setTimestamp(System.currentTimeMillis());
        apiResult.setServiceId(ApplicationConfig.SERVICE_NAME);
        return apiResult;
    }

}
